package com.ctrip.ec.api.mobile.common;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;


/**
 * Created by jiangzy on 2018/5/2.
 */
public final class Encryption {

    private  static  final String keyStr = "01234567";

    public  static  String desEncript(String src) throws  Exception{

        try {

            final  java.util.Base64.Encoder encoder =     java.util.Base64.getEncoder();
          //  Base64.decodeBase64()

            byte[] keyBytes = keyStr.getBytes();
            DESKeySpec keySpec=new DESKeySpec(keyBytes);
            SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("DES");
            SecretKey key=keyFactory.generateSecret(keySpec);

            Cipher cipher=Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(keySpec.getKey()));
            byte[] result=cipher.doFinal(src.getBytes("utf-8"));

            return encoder.encodeToString(result);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("exception:"+e.toString());
            throw e;
        }
    }

    public  static  String md5(String src) throws  Exception{
        return desEncript(src);
    }



    public  static  String desDecript(String src) throws  Exception{
        try {
         //   byte[] keyBytes = keyStr.getBytes();

            final  java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();

            byte[] keyBytes = keyStr.getBytes();
            DESKeySpec keySpec=new DESKeySpec(keyBytes);
            SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("DES");
            SecretKey key=keyFactory.generateSecret(keySpec);

            Cipher cipher=Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(keyBytes));
            byte[] result=cipher.doFinal(decoder.decode(src));
            return new String(result,"utf-8");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("exception:"+e.toString());
            throw  e;
        }
    }


}
